﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenExpressApp.Template;
using OpenExpressApp.WPF.Controls;
using System.ComponentModel;
using System.Windows.Controls;
using System.Windows;
using Csla.Core;
using OpenExpressApp.MetaModel;
using System.Collections;
using System.Diagnostics;
using Itenso.Windows.Input;
using Csla.OpenExpressApp;

namespace OpenExpressApp.Module.WPF.Templete
{
    public class ListDetailFormController : ListFormController, IListDetailFrameController
    {
        private Panel _detailRegion;

        private DetailViewController _detailViewController;

        public ListDetailFormController(IWindowTemplate windowTemplate)
            : base(windowTemplate)
        {
            this.View.SelectedItemChanged += View_SelectedItemChanged;
        }

        public event EventHandler<DataLoadedEventArgs> DataLoaded
        {
            add
            {
                this._detailViewController.DataLoaded += value;
            }
            remove
            {
                this._detailViewController.DataLoaded -= value;
            }
        }

        public event EventHandler DataChanged
        {
            add
            {
                this._detailViewController.DataChanged += value;
            }
            remove
            {
                this._detailViewController.DataChanged -= value;
            }
        }

        protected override void CreateViewController()
        {
            base.CreateViewController();

            this._detailViewController = new DetailViewController(this.View.DetailView);
            this._detailViewController.DataLoaded += DetailViewContoller_DataLoaded;

            this._detailRegion = this.FrameTemplate.GetRegion(ViewRegionNames.DetailRegion) as Panel;
            this._detailRegion.Children.Add(this._detailViewController.Control);
        }

        /// <summary>
        /// 异步获取右边DetailView中的数据
        /// </summary>
        /// <param name="coerce"></param>
        public void AsyncGetCurObject(bool coerce)
        {
            var selectedEntity = this.View.CurrentObject as BusinessBase;
            if (selectedEntity != null &&
                selectedEntity.IsNew == false &&
                (coerce || selectedEntity.IsObjectLazy)
                )
            {
                ////如果处于异步加载时期，停止加载
                //if (this._detailViewController.IsLoadingData)
                //{
                //    this._detailViewController.CancelLoading();
                //}

                //重新异步加载新的数据
                var id = selectedEntity.GetPropertyValue(DBConvention.FieldName_Id);
                this._detailViewController.AsyncGetObject(id);
            }
            else
            {
                //selectedEntity.BeginEdit();
                this.View.DetailView.Data = selectedEntity;
            }
        }

        private void DetailViewContoller_DataLoaded(object sender, DataLoadedEventArgs e)
        {
            //由于异步获取DetailData，所以此时的CurrentObject不一定是dataprovider获取时的那个对象了
            var dbEntity = e.Data as BusinessBase;
            if (null == dbEntity) return;
            Debug.WriteLine("DataLoaded:" + dbEntity.ToString());

            var oldEntity = this.View.CurrentObject as BusinessBase;

            //if (oldEntity == null)
            //{
            //    var id = dbEntity.GetPropertyValue(DBConvention.FieldName_Id);
            //    oldEntity = this.View.Data.OfType<BusinessBase>().First(
            //        o => o.GetPropertyValue(DBConvention.FieldName_Id).Equals(id));
            //}

            if (dbEntity.GetPropertyValue(DBConvention.FieldName_Id).Equals(oldEntity.GetPropertyValue(DBConvention.FieldName_Id)))
            {
                oldEntity.MergeOldObject(dbEntity);
                //oldEntity.BeginEdit();

                e.Data = oldEntity;
            }
        }

        /// <summary>
        /// 切换左边视图
        /// 
        /// 保存选择的旧实体，并异步获取新的实体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void View_SelectedItemChanged(object sender, SelectedItemChangedEventArgs e)
        {
            //保存选择的旧实体
            var oldEntity = e.OldItem;
            if (oldEntity != null)
            {
               // oldEntity.ApplyEdit();  //编辑时切换到列表时对象处于编辑状态
                //如果不是新增后立即删除的可更改对象则自动保存
                if (oldEntity.IsDirty)
                {
                    //oldEntity.MergeOldObject((oldEntity as ISavable).Save() as BusinessBase);
                    DiffSaveCommand.Execute(oldEntity);
                }
            }

            //异步获取新的实体
            if (e.NewItem != null)
            {
                this.AsyncGetCurObject(false);
            }
        }
    }
}
